import axios from 'axios'
import { ElMessage } from 'element-plus'

axios.defaults.timeout = 5000

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_API,
  timeout: 10000, 
  headers: {
    'Content-Type': 'application/json',
  }
})

// 请求
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log(error) 
    return Promise.reject(error)
  }
)

// 响应
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code !== '') {
      if (res.code == 500) {
        ElMessage({
          message: res.msg,
          type: 'error',
          duration: 1 * 1000
        })
      } else {
        return res
      }
    } else {
      ElMessage({
        message: res.msg,
        type: 'error',
        duration: 1 * 1000
      })
      return res
    }
  },
  error => {
    if (!error.message.includes('timeout')) {
      ElMessage({
        message: '服务器暂无响应，请稍后重试',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
